<template>
  <div class="virtual-lab-container">
    <h2 class="lab-title">伏安法测电阻</h2>

    <div class="scene-wrapper">
      <div class="circuit-panel">
        <svg class="circuit-diagram" viewBox="0 0 400 250">
          <defs>
            <path id="wire-path" d="M 20 50 H 380 V 200 H 20 V 50 Z" fill="none" />
          </defs>
          <use href="#wire-path" class="wire" />
          <g v-if="isSwitchClosed">
            <circle v-for="i in 8" :key="i" class="electron" r="2.5">
              <animateMotion
                :dur="`${4 + i * 0.2}s`"
                repeatCount="indefinite"
                path="M 20 50 H 380 V 200 H 20 V 50 Z"
              />
            </circle>
          </g>

          <g class="component power-supply" transform="translate(20, 105)">
            <path d="M 0 20 V -20 M 8 10 V -10" stroke="#333" stroke-width="2"/>
            <text x="15" y="5">E</text>
          </g>
          <g class="component switch" :class="{closed: isSwitchClosed}" transform="translate(120, 50)" @click="toggleSwitch">
            <circle cx="0" cy="0" r="4" />
            <circle cx="40" cy="0" r="4" />
            <line x1="5" y1="0" x2="35" y2="0" class="movable" />
            <text x="15" y="20">S</text>
          </g>
          <g class="component resistor" transform="translate(280, 50)">
            <rect x="0" y="-8" width="60" height="16" rx="2" stroke="#666" stroke-width="1.5" fill="#fff"/>
            <text x="20" y="20">Rₓ</text>
          </g>
          <g class="component ammeter" transform="translate(380, 125)">
            <circle cx="0" cy="0" r="20" stroke="#333" stroke-width="2" fill="#f0f4f8"/>
            <text x="0" y="-3" class="meter-label">A</text>
            <text x="0" y="12" class="readout">{{ current.toFixed(2) }}</text>
          </g>
          <g class="component rheostat" transform="translate(200, 200)">
            <rect x="0" y="-8" width="120" height="16" rx="2" stroke="#666" stroke-width="1.5" fill="#fff"/>
            <line x1="0" y1="-15" x2="120" y2="-15" stroke-width="2" />
            <path :d="`M ${rheostatValue * 1.2} -15 L 60 0`" stroke-width="1.5" class="rheostat-slider"/>
            <text x="50" y="20">R</text>
          </g>
          <g class="component voltmeter" transform="translate(310, 135)">
            <circle cx="0" cy="0" r="22" stroke="#333" stroke-width="2" fill="#f0f4f8"/>
            <text x="0" y="-4" class="meter-label">V</text>
            <text x="0" y="13" class="readout">{{ voltageAcrossResistor.toFixed(2) }}</text>
            <path d="M 0 -22 V -85 H -30" class="wire thin"/>
            <path d="M 0 22 V 65 H -110" class="wire thin"/>
          </g>
        </svg>
      </div>
    </div>

    <div class="info-panel">
      <div class="panel-left">
        <p><strong>实验状态:</strong> {{ phenomenonText }}</p>
        <p><strong>理论公式:</strong> R = U / I</p>
        <div class="control-item">
          <label for="rheostat">滑动变阻器 ({{ rheostatResistance.toFixed(1) }} Ω)</label>
          <input
            type="range"
            id="rheostat"
            min="0"
            max="100"
            step="1"
            v-model="rheostatValue"
            :disabled="!isSwitchClosed"
          />
        </div>
        <div class="actions">
            <button @click="recordData" :disabled="!isSwitchClosed">记录数据</button>
            <button @click="resetExperiment" class="reset-btn">重置实验</button>
        </div>
      </div>
      <div class="panel-right">
        <div class="live-data">
          <div class="display-box">
            <span>待测电阻 Rₓ (目标值)</span>
            <strong>{{ unknownResistance.toFixed(1) }} Ω</strong>
          </div>
          <div class="display-box">
            <span>测量结果 R = U / I</span>
            <strong :class="{ 'error-text': !isSwitchClosed }">
              {{ isSwitchClosed ? measuredResistance.toFixed(2) + ' Ω' : '电路断开' }}
            </strong>
          </div>
        </div>
        <div class="data-table-container">
          <table>
            <thead>
              <tr>
                <th>序号</th>
                <th>电压 (V)</th>
                <th>电流 (A)</th>
                <th>电阻 (Ω)</th>
              </tr>
            </thead>
            <tbody>
              <tr v-if="dataLog.length === 0">
                <td colspan="4">暂无数据，请闭合开关后记录</td>
              </tr>
              <tr v-for="(log, index) in dataLog" :key="index">
                <td>{{ index + 1 }}</td>
                <td>{{ log.voltage.toFixed(2) }}</td>
                <td>{{ log.current.toFixed(2) }}</td>
                <td>{{ log.resistance.toFixed(2) }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';

// --- 状态管理 ---
const experimentState = ref('idle'); // 'idle', 'running', 'finished'
const phenomenonText = ref('请点击开关 S 闭合电路。');
const isSwitchClosed = ref(false);
const rheostatValue = ref(50); // 滑动变阻器的百分比 (0-100)
const unknownResistance = ref(10); // 待测电阻的 "真实" 值
const dataLog = ref([]);

// --- 物理常量与计算属性 ---
const POWER_SUPPLY_VOLTAGE = 6.0; // 电源电压 6V
const MAX_RHEOSTAT_RESISTANCE = 20.0; // 滑动变阻器最大值 20Ω

const rheostatResistance = computed(() => {
  return (rheostatValue.value / 100) * MAX_RHEOSTAT_RESISTANCE + 0.1;
});

const totalResistance = computed(() => {
  return unknownResistance.value + rheostatResistance.value;
});

const current = computed(() => {
  if (!isSwitchClosed.value) return 0;
  return POWER_SUPPLY_VOLTAGE / totalResistance.value;
});

const voltageAcrossResistor = computed(() => {
  if (!isSwitchClosed.value) return 0;
  return current.value * unknownResistance.value;
});

const measuredResistance = computed(() => {
  if (current.value < 0.001) return 0;
  return voltageAcrossResistor.value / current.value;
});

// --- 实验逻辑 ---
function toggleSwitch() {
  isSwitchClosed.value = !isSwitchClosed.value;
  if (isSwitchClosed.value) {
    phenomenonText.value = '电路已连通，请调节滑块并记录数据。';
    experimentState.value = 'running';
  } else {
    phenomenonText.value = '电路已断开，请点击开关 S 闭合电路。';
    experimentState.value = 'idle';
  }
}

function recordData() {
  if (!isSwitchClosed.value) return;
  dataLog.value.push({
    voltage: voltageAcrossResistor.value,
    current: current.value,
    resistance: measuredResistance.value
  });
  phenomenonText.value = `成功记录第 ${dataLog.value.length} 组数据。`;
}

function resetExperiment() {
  unknownResistance.value = Math.random() * 10 + 5; // 随机电阻值 (5-15Ω)
  isSwitchClosed.value = false;
  rheostatValue.value = 50;
  dataLog.value = [];
  experimentState.value = 'idle';
  phenomenonText.value = '实验已重置，请点击开关 S 闭合电路。';
}

onMounted(resetExperiment);

</script>

<style scoped>
/* --- 基础布局和主题样式 (源于钠水反应示例) --- */
.virtual-lab-container {
  width: 100%;

  margin: 20px auto;
  display: flex;
  flex-direction: column;
  background: #fdfdfd;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0,0,0,0.1);
  padding: 20px;
}
.lab-title {
  text-align: center;
  color: #334e68;
  margin-top: 0;
  margin-bottom: 20px;
}
.scene-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-grow: 1;
  margin-bottom: 20px;
}

/* --- 电路图面板 --- */
.circuit-panel {
  background-color: #f0f4f8;
  border-radius: 8px;
  padding: 10px;
  width: 100%;
  max-width: 500px;
}
.circuit-diagram {
  width: 100%;
  height: auto;
}

/* --- 统一信息与控制面板 (底部) --- */
.info-panel {
  padding: 20px;
  background-color: #f0f4f8;
  border-radius: 8px;
  display: flex;
  gap: 30px;
}
.panel-left, .panel-right {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 15px;
}
.info-panel p {
  margin: 0;
  color: #486581;
}
.info-panel p strong {
  color: #334e68;
}

/* --- 控制项 --- */
.control-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.control-item label {
  color: #486581;
  font-weight: 500;
}
input[type="range"] {
  cursor: pointer;
  accent-color: #4A90E2;
}
input[type="range"]:disabled {
  cursor: not-allowed;
  accent-color: #a0a0a0;
}

/* --- 按钮 --- */
.actions {
    margin-top: auto; /* Push buttons to the bottom of the left panel */
    display: flex;
    gap: 10px;
}
.info-panel button {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  color: white;
  cursor: pointer;
  transition: background-color 0.3s;
  font-size: 14px;
  font-weight: 500;
}
.info-panel button:disabled {
  background-color: #a0a0a0;
  cursor: not-allowed;
}
.info-panel button:not(:disabled) {
    background-color: #4A90E2;
}
.info-panel button:hover:not(:disabled) {
    background-color: #357ABD;
}
.info-panel .reset-btn {
    background-color: #e74c3c;
}
.info-panel .reset-btn:hover:not(:disabled) {
    background-color: #c0392b;
}

/* --- 实时数据展示 --- */
.live-data {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.display-box {
  padding: 12px;
  border: 1px solid #d1d9e6;
  border-radius: 6px;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.display-box span {
  color: #829ab1;
  font-size: 14px;
}
.display-box strong {
  color: #334e68;
  font-size: 1.1em;
  font-family: 'Courier New', monospace;
}
.error-text {
  color: #e74c3c !important;
}

/* --- 数据表格 --- */
.data-table-container {
  flex-grow: 1; /* Allow table to fill remaining space */
  max-height: 160px;
  overflow-y: auto;
  border: 1px solid #d1d9e6;
  border-radius: 6px;
  background-color: #fff;
}
table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}
th, td {
  padding: 8px 12px;
  text-align: center;
  border-bottom: 1px solid #e2e8f0;
}
thead th {
  background-color: #e2e8f0;
  color: #486581;
  position: sticky;
  top: 0;
  z-index: 1;
}
tbody tr:last-child td {
  border-bottom: none;
}
tbody tr:nth-child(even) {
  background-color: #f8fafc;
}
td[colspan="4"] {
    color: #829ab1;
    padding: 20px;
}


/* --- SVG 电路图具体样式 --- */
.wire { fill: none; stroke: #667eea; stroke-width: 2.5px; }
.wire.thin { stroke: #a3bffa; stroke-width: 1.5px; }
.component text { font-family: 'Segoe UI', sans-serif; font-size: 14px; fill: #334e68; text-anchor: middle; user-select: none; }
.meter-label { font-size: 18px; font-weight: bold; }
.readout { font-family: 'Courier New', monospace; font-size: 13px; font-weight: bold; fill: #2c5282; }
.switch { cursor: pointer; }
.switch .movable { stroke: #e53e3e; stroke-width: 4px; stroke-linecap: round; transform-origin: 0 0; transition: transform 0.3s ease; transform: rotate(-45deg); }
.switch.closed .movable { transform: rotate(0deg); stroke: #4caf50; }
.rheostat-slider { stroke: #333; stroke-width: 2px;}
.electron { fill: #667eea; animation: pulse 1s infinite alternate; }
@keyframes pulse {
    from { r: 2.5px; opacity: 1;}
    to { r: 3px; opacity: 0.8;}
}
</style>